package com.oazon.moco.serialport;

import java.util.List;

import android.app.Service;
import android.content.Intent;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.IBinder;

import com.oazon.common.Logger;
import com.oazon.common.TaskHelper;

public class WeightServer extends Service implements SensorEventListener {

	private static final String TAG = "WeightServer";

	private static final long UPTATE_INTERVAL_TIME = 200; 

	private SensorManager mSensorManager;
	double CurrTime, LastTime;
	float AccThres = 3; // 加速度阈值
	float AccTime = 10; // 时间间隔阈值，单位毫秒
	Intent service = null;

	int count = 0;
	int moveCount = 0;
	int standCount = 0;

	private long lastUpdateTime;

	@Override
	public void onCreate() {
		LastTime = System.currentTimeMillis();
		mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
		List<Sensor> sensors = mSensorManager
				.getSensorList(Sensor.TYPE_ACCELEROMETER);

		// sensor1
		for (Sensor s : sensors) {
			mSensorManager.registerListener(this, s,
					SensorManager.SENSOR_DELAY_NORMAL);
		}
		startTime();
		super.onCreate();
	}

	@Override
	public IBinder onBind(Intent arg0) {
		return null;
	}

	@Override
	public void onAccuracyChanged(Sensor arg0, int arg1) {
	}

	@Override
	public void onSensorChanged(SensorEvent event) {
		if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
			threadCount = 0;
			
			// 现在检测时间
			long currentUpdateTime = System.currentTimeMillis();
			// 两次检测的时间间隔
			long timeInterval = currentUpdateTime - lastUpdateTime;
			// 判断是否达到了检测时间间隔
			if (timeInterval < UPTATE_INTERVAL_TIME)
				return;
			// 现在的时间变成last时间
			lastUpdateTime = currentUpdateTime;
			// 获取加速度数值，以下三个值为重力分量在设备坐标的分量大小
			// 获取加速度数值，以下三个值为重力分量在设备坐标的分量大小
			float x = event.values[0];
			float y = event.values[1];
			float z = event.values[2];
//			Logger.d(TAG, "x=" + x + "=y=" + y + "=z=" + z);
			
			double angleZ = Math.atan2( Math.abs(z), Math.sqrt(x * x + y * y))*(z/ Math.abs(z));
			double angleX = Math.atan2( Math.abs(x), Math.sqrt(z * z + y * y))*(x/ Math.abs(x));
			double angleY = Math.atan2( Math.abs(y), Math.sqrt(x * x + z * z))*(y/ Math.abs(y));
			angleZ = angleZ * 180 / Math.PI;
			angleX = angleX * 180 / Math.PI;
			angleY = angleY * 180 / Math.PI;
			Logger.d(TAG, "angleZ=="+(int)angleZ+"==angleX=="+(int)angleX+"==angleY=="+(int)angleY);
			onSignal(angleX, angleY, angleZ);
		}
	}

	boolean isMoveState = false;

	private void onSignal(double angleX, double angleY, double angleZ) {
		if ((angleX >= 10 || angleX <= -10) || (angleY >= 40 || angleY <= 20) || (angleZ >= 75 || angleZ <= 55)) {
			standCount = 0;
			if (!isMoveState) {// 防止多次调度串口的停止
				// 移动状态
				if (moveCount < 2) {// 连续3次进入移动状态。
					moveCount++;
					return;
				}
				moveCount = 0;
				isMoveState = true;
				Logger.d(TAG, "speed=Move__Move__Move__Move__Move__Move======");
				SerialControll.getInstance().stopControl();
			}
		} else {
			moveCount = 0;
			if (isMoveState) {
				// 正常状态
				if (standCount < 1) {// 连续2次进入静止状态。
					standCount++;
					return;
				}
				standCount = 0;
				isMoveState = false;
				Logger.d(TAG, "speed=stand___Stand_Stand___Stand======");
				SerialControll.getInstance().startControl();
			}
		}
	}

	boolean isRunning = false;
	int threadCount = 0;

	Runnable standRunnable = new Runnable() {

		@Override
		public void run() {
			while (isRunning) {
				if (threadCount >= 5) {
					onSignal(0, 30, 65);
					onSignal(0, 30, 65);
					threadCount = 0;
				}
				threadCount++;
				try {
					Thread.sleep(200);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}

		}
	};

	private void startTime() {
		isRunning = true;
		threadCount = 0;
		TaskHelper.exec(standRunnable);
	}

	private void stopTime() {
		isRunning = false;
		threadCount = 0;
	}

	@Override
	public void onDestroy() {
		stopTime();
		super.onDestroy();
	}
}
